package com.sgb.member.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.sgb.member.MemberConfig;
import com.sgb.member.R;
import com.sgb.member.databinding.ActivityPersonInviteJoin2Binding;
import com.sgb.member.entity.ParamDtosEntity;
import com.sgb.member.entity.PeronMemberJoinEntity;
import com.sgb.member.entity.PersonMemberBean;
import com.sgb.member.entity.QualityMemberBean;
import com.sgb.member.ui.adapter.NewAddAdapter;
import com.sgb.member.view_model.PersonInviteJoinModel2;
import com.sgb.member.weight.NumberInputFilter;
import com.sgb.member.weight.SimpleResult;
import com.swgk.core.base.AppActivity;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.CheckUtils;
import com.swgk.core.util.ClickUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.util.StringUtil;
import com.swgk.core.view.selection.CommonPopEntity;
import com.swgk.core.view.selection.CopyUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 企业 申请、邀请 个人 无审批
 * 申请、邀请 共有一个页面
 */
public class ComApplyOrInvitePersonActivity extends AppActivity implements ItemInputTextView.OnWholeItemClickListener {
    private PersonInviteJoinModel2 viewModel;
    private ActivityPersonInviteJoin2Binding mBinding;
    private List<CommonPopEntity> memberTypes;
    private QualityMemberBean memberBean;
    private boolean isFlag; // 是否重复提交
    private int type;// 0 邀请  1 申请
    private PeronMemberJoinEntity mJoinEntity;
    private List<ParamDtosEntity> viewList = new ArrayList<>();//自定义参数

    public static void start(Activity context, QualityMemberBean memberBean, boolean isFlag, int type) {
        Intent intent = new Intent(context, ComApplyOrInvitePersonActivity.class);
        intent.putExtra("bean", memberBean);
        intent.putExtra("isFlag", isFlag);
        intent.putExtra("type", type);
        context.startActivityForResult(intent, MemberConfig.REQ_SERVICE);
    }

    @Override
    protected void init() {
        super.init();
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        //设置沉浸式状态栏的上移问题
        setTileImmerse(true);
    }

    @Override
    protected void initView() {
        super.initView();
        memberBean = (QualityMemberBean) getIntent().getSerializableExtra("bean");
        isFlag = getIntent().getBooleanExtra("isFlag", false);
        type = getIntent().getIntExtra("type", 0);
        if (memberBean == null) {
            finish();
            return;
        }
        viewModel = new ViewModelProvider(this).get(PersonInviteJoinModel2.class);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_person_invite_join_2);
        mBinding.setViewModel(memberBean);
        mBinding.setIsApplay(type==0?false:true);
        mBinding.activityBar.titleView.setText(type == 0 ? "邀请加盟" : "申请加盟");
        mBinding.activityBar.ivBack.setOnClickListener(v -> onBackPressed());
        mBinding.includePerson.clPersonInfo.setOnClickListener(v -> MemberConfig.getInstance().startWebsiteInfo(getActivity(), memberBean.getNo(), 0));
        setVisibleUI();
        initEntityInfo();
        viewModel.getPersonProfile(memberBean.getNo());
        viewModel.getMemberLevelList();
        mBinding.submit.setOnClickListener(v -> submitInfo());
        mBinding.tvAddView.setOnClickListener(v -> adapter.addData());

        initRecyclerView();
        receiverLiveData();

    }

    private void setVisibleUI() {
        if (type == 0) {//邀请
            mBinding.itemCompany.setLabelName("邀请会员");
            mBinding.tvShuoMingTitle.setText("邀请说明");
            mBinding.tvYeWu.setText("合作业务");
            mBinding.cfkNotes.setHint("请输入邀请说明");
        }
    }

    private NewAddAdapter adapter;
    private void initRecyclerView() {
        adapter = new NewAddAdapter(this, viewList);
        mBinding.rvAdd.setAdapter(adapter);
    }

    private void receiverLiveData() {
        viewModel.msgLiveData.observe(this, s -> MToast.showToast(this, s));
        viewModel.isLoadLiveData.observe(this, b ->showLoadDialog(b));
        viewModel.simpleResultMutableLiveData.observe(this, commonPopEntitySimpleResult -> showMemberLeverPop(mBinding.itemLever,commonPopEntitySimpleResult));
        viewModel.memberProfileLiveData.observe(this, data -> setMemberProfile(data));
        viewModel.showEmptyViewLiviData.observe(this, aBoolean -> showEmptyView());
        viewModel.memberJoinSuccessLiveData.observe(this, aBoolean -> memberJoinSuccess());
        viewModel.levelLiveData.observe(this, commonPopEntities -> mPop4 = commonPopEntities);
    }
    private void showLoadDialog(boolean b){
        if (b) {
            DialogHelper.showProgressDialog(this, "数据获取中...");
        } else {
            DialogHelper.dismissProgressDialog();
        }
    }


    /**
     * 初始化获取企业信息
     */
    private void initEntityInfo() {
        String companyNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
        String companyName = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NAME, "");
        String userName = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.REAL_NAME, "");
        String userPhone = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_PHONE, "");

        mJoinEntity = new PeronMemberJoinEntity();
        mJoinEntity.setNo("");
        mJoinEntity.setApplyCompanyName(companyName); // 申请企业名称
        mJoinEntity.setApplyCompanyNo(companyNo); // 申请企业no
        mJoinEntity.setApplyCompanyBusinessOwner(userName);
        mJoinEntity.setApplyCompanyContacts(userName);
        mJoinEntity.setApplyCompanyPhone(userPhone);
        mJoinEntity.setRelation("1");//供需关系 1.供方会员 2.需方会员
        mJoinEntity.setLevel("普通会员");
        mJoinEntity.setApplyType("1"); //申请类型 1企业申请.邀请 2 个人申请.邀请
        mJoinEntity.setJoinWay(type == 0 ? "2" : "1"); //途径方式 1:申请 2：邀请
        mJoinEntity.setInviteContent(""); //邀请内容


        mBinding.itemDanWan.setContent(companyName); //申请单位指我当前的单位
        mBinding.itemUser.setContent(getText(userName)); //负责人指我当前公司的
        mBinding.itemContacts.setContent(userName);
        mBinding.itemContactsPhone.setContent(userPhone);
        mBinding.itemCompany.setContent(memberBean.getCompanyName());
        mBinding.itemRelation.setContent("供方会员"); // 默认选中供方会员
        mBinding.itemLever.setContent("普通会员"); // 默认选中普通会员
        mBinding.itemLever.setOnWholeItemClickListener(this);
        mBinding.itemRelation.setOnWholeItemClickListener(this);
        mBinding.itemType.setOnWholeItemClickListener(this);
        mBinding.itemLeverSetting.setOnWholeItemClickListener(this);
        mBinding.itemContacts.setInfilterType(ItemInputTextView.TYPE_TEXT);
        mBinding.itemContactsPhone.setInputType(InputType.TYPE_CLASS_PHONE);
        mBinding.itemContactsPhone.setMaxSize(11);
        mBinding.itemCooperationExpected.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        mBinding.itemMemberRequirements.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        mBinding.itemCooperationExpected.setFilters(new NumberInputFilter[]{new NumberInputFilter(99999999999.99, 0.01, 2)});
        mBinding.itemMemberRequirements.setFilters(new NumberInputFilter[]{new NumberInputFilter(99999999999.99, 0.01, 2)});
        mBinding.itemCooperationExpected.setInfilterType(ItemInputTextView.TYPE_NUM);
        mBinding.itemMemberRequirements.setInfilterType(ItemInputTextView.TYPE_NUM);
        mBinding.itemMemberRequirements.setInputType(InputType.TYPE_CLASS_NUMBER);
        mBinding.itemCooperationExpected.setInputType(InputType.TYPE_CLASS_NUMBER);
        mBinding.itemMemberRequirements.setMaxSize(10);
        mBinding.itemCooperationExpected.setMaxSize(10);
    }


    /**
     * 更新会员信息
     */
    public void setMemberProfile(PersonMemberBean data) {
        String concat = getText(data.getRealName());
        String phone = getText(data.getTelephone());
        mBinding.includePerson.tvName.setText(concat);
        mBinding.includePerson.tvPhone.setText(phone);
        mBinding.includePerson.tvCompany.setText("/");
        mBinding.itemCompany.setContent(concat);

        // 个人用户信息
        mJoinEntity.setUserNo(data.getUserNo());
        mJoinEntity.setUserContactName(data.getRealName());
        mJoinEntity.setUserContactPhone(data.getTelephone());
        mJoinEntity.setUserName(data.getRealName());
        mJoinEntity.setUserPhone(data.getTelephone());

    }

    private String getText(String text) {
        if (StringUtil.isEmpty(text)) {
            return "暂无数据";
        }
        return text;
    }

    public static String formatListToString(List<String> str) {
        if (str == null || str.size() == 0) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        for (String s : str) {
            sb.append(s).append(",");
        }
        return sb.substring(0, sb.length() - 1);
    }

    /**
     * 个人加盟成功
     */
    public void memberJoinSuccess() {
        MToast.showToast(this, "提交成功");
        Intent intent = new Intent();
        intent.putExtra(MemberConfig.JUMP_RECORD_APPROVAL, true);
        setResult(RESULT_OK, intent);
        finish();
    }

    @Override
    public void OnWholeItemClick(View view) {
        int id = view.getId();
        if (id == R.id.item_lever) {
            // 会员等级
            showMemberLeverPop(mBinding.itemLever, (commonPopEntity, objects) -> {
                mJoinEntity.setLevel(commonPopEntity.getTypeName());
            });
        } else if (id == R.id.item_relation) {
            showSupplyDemandPop(mBinding.itemRelation, (commonPopEntity, objects) -> {
                // 设置供需关系
                if (!TextUtils.equals(commonPopEntity.getNo(), mJoinEntity.getRelation())) {
                    memberTypes = new ArrayList<>();
                    mBinding.itemType.setContent("");
                }
                mJoinEntity.setRelation(commonPopEntity.getNo());
            });
        } else if (id == R.id.item_type) {
            if (TextUtils.isEmpty(mBinding.itemRelation.getContent())) {
                MToast.showToast(this, "请选择供需关系");
                return;
            }
            if (TextUtils.equals("1", mJoinEntity.getRelation())) {
                // ascription 0 供方 1需方
                ChooseMemberTypeActivity.start(this, memberTypes, "0", MemberConfig.REQ_MEMBER_TYPE);
            } else {
                ChooseMemberTypeActivity.start(this, memberTypes, "1", MemberConfig.REQ_MEMBER_TYPE);
            }
        }else if(id == R.id.item_lever_setting){
            // 会员等级诉求
            showMemberLeverPop(mBinding.itemLeverSetting, (commonPopEntity, objects) -> {
                mJoinEntity.setAppealLevel(commonPopEntity.getTypeName());
            });
        }
    }

    private void submitInfo() {
        if (ClickUtils.isDoubleClick()) {
            return;
        }
        if (TextUtils.isEmpty(mBinding.itemLever.getContent())) {
            MToast.showToast(this, "请选择会员等级");
            return;
        }
        if (TextUtils.isEmpty(mBinding.itemRelation.getContent())) {
            MToast.showToast(this, "请选择供需关系");
            return;
        }
        if (TextUtils.isEmpty(mBinding.itemType.getContent())) {
            MToast.showToast(this, "请选择会员类型");
            return;
        }
        if (type == 1) {//申请
            if (TextUtils.isEmpty(mBinding.itemLeverSetting.getContent())) {
                MToast.showToast(this, "请选择会员等级诉求");
                return;
            }
        }
        if (TextUtils.isEmpty(mBinding.itemContacts.getContent().trim())) {
            Toast.makeText(this, "请填写联系人", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(mBinding.itemContactsPhone.getContent().trim())) {
            Toast.makeText(this, "请填写联系电话", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!CheckUtils.isMobile(mBinding.itemContactsPhone.getContent().trim())) {
            Toast.makeText(this, "请填写正确的联系电话", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(mBinding.cfkNotes.getEditContent().trim())) {
            if(type==0){
                Toast.makeText(this, "请输入邀请说明", Toast.LENGTH_SHORT).show();
            }else {
                Toast.makeText(this, "请输入申请说明", Toast.LENGTH_SHORT).show();
            }

            return;
        }

        if(type==0){
            mJoinEntity.setCooperationExpected(mBinding.itemCooperationExpected.getContent());    // 合作预期[v1.0.9]
            mJoinEntity.setMembershipRequirements(mBinding.itemMemberRequirements.getContent());// 会费要求[v1.0.9]
            mJoinEntity.setCooperationBusiness(mBinding.cfkBusiness.getEditContent());    // 合作业务[v1.0.9]
            mJoinEntity.setInvitationInstructions(mBinding.cfkNotes.getEditContent().trim());
        }else {
            mJoinEntity.setApplyBusiness(mBinding.cfkBusiness.getEditContent().trim()); // 申请业务
            mJoinEntity.setApplicationDescription(mBinding.cfkNotes.getEditContent().trim());
        }

        mJoinEntity.setUserContactName(mBinding.itemContacts.getContent());//联系人
        mJoinEntity.setUserContactPhone(mBinding.itemContactsPhone.getContent()); //联系电话
        if (!adapter.submitYanZheng()) {
            return;
        }
        for (ParamDtosEntity item : viewList) {
            if (TextUtils.isEmpty(item.getContent()) && TextUtils.isEmpty(item.getTitle())) {
                viewList.remove(item);
            }
        }
        mJoinEntity.setParamDtos(viewList);
        Map<String, List<CommonPopEntity>> typeMap = null;
        if (isFlag) {
            if (memberTypes != null && memberTypes.size() > 0) {
                typeMap = CopyUtils.memberTypeToJson(memberTypes);
            }
        } else {
            typeMap = CopyUtils.memberTypeToJson(memberTypes);
        }
        if (typeMap != null) {
            mJoinEntity.setFirstCategory(getCategoryNos(typeMap.get("firstCategory")));
            mJoinEntity.setSecondCategory(getCategoryNos(typeMap.get("secondCategory")));
            mJoinEntity.setThirdCategory(getCategoryNos(typeMap.get("thirdCategory")));
            mJoinEntity.setFourCategory(getCategoryNos(typeMap.get("fourCategory")));
            mJoinEntity.setFiveCategory(getCategoryNos(typeMap.get("fiveCategory")));
        }

        viewModel.memberJoin(mJoinEntity);
    }

    private List<String> getCategoryNos(List<CommonPopEntity> list) {
        List<String> strings = new ArrayList<>();
        if (list == null || list.size() == 0) {
            return strings;
        }
        for (CommonPopEntity popEntity : list) {
            strings.add(popEntity.getNo());
        }
        return strings;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if (resultCode == RESULT_OK && requestCode == MemberConfig.REQ_MEMBER_TYPE) {
            memberTypes = (List<CommonPopEntity>) intent.getSerializableExtra("MEMBER_DATA");
            if (memberTypes != null && memberTypes.size() > 0) {
                StringBuilder sb = new StringBuilder();
                for (CommonPopEntity memberType : memberTypes) {
                    sb.append(memberType.getTypeName()).append("、");
                }
                String str = sb.substring(0, sb.toString().length() - 1);
                mBinding.itemType.setContent(str);
            } else {
                mBinding.itemType.setContent("");
            }
        }
    }

    public void showEmptyView() { }

    private OptionsPickerView<CommonPopEntity> mOption4;
    private List<CommonPopEntity> mPop4;

    public void showMemberLeverPop(ItemInputTextView textView,SimpleResult<CommonPopEntity> simpleResult) {
        if (mPop4 == null) {
            viewModel.getMemberLevelList();
            return;
        }
        mOption4 = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
            String name = mPop4.get(options1).getPickerViewText();
            textView.setContent(name);
            if (simpleResult != null) {
                simpleResult.onResult(mPop4.get(options1));
            }
        }).setCancelColor(getResources().getColor(R.color.color_title_small))
                .setLineSpacingMultiplier(2.2f)
                .setCancelColor(0xFF666666)
                .setTitleColor(0xFF969696)
                .setSubCalSize(15)
                .setTitleSize(15)
                .setContentTextSize(15)
                .build();
        mOption4.setTitleText("会员等级");
        mOption4.setPicker(mPop4);
        mOption4.setSelectOptions(0);
        mOption4.show();
    }

    private OptionsPickerView<CommonPopEntity> mOption5;
    private List<CommonPopEntity> mPop5;

    public void showSupplyDemandPop(ItemInputTextView textView, SimpleResult<CommonPopEntity> simpleResult) {
        if (mOption5 == null) {
            // 供需关系  1供方  2需方
            mPop5 = new ArrayList<>();
            mPop5.add(new CommonPopEntity("1", "供方会员"));
            mPop5.add(new CommonPopEntity("2", "需方会员"));
            mOption5 = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
                String no = mPop5.get(options1).getNo();
                String name = mPop5.get(options1).getTypeName();
                textView.getContent_edt().setText(name);
                if (simpleResult != null) {
                    simpleResult.onResult(mPop5.get(options1));
                }
            }).setCancelColor(getResources().getColor(R.color.color_title_small))
                    .setLineSpacingMultiplier(2.2f)
                    .setCancelColor(0xFF666666)
                    .setTitleColor(0xFF969696)
                    .setSubCalSize(15)
                    .setTitleSize(15)
                    .setContentTextSize(15)
                    .build();
            mOption5.setTitleText("供需关系");
        }
        mOption5.setPicker(mPop5);
        mOption5.setSelectOptions(0);
        mOption5.show();
    }


}
